package com.xmy.study.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.study.entity.Course;
import com.xmy.study.mapper.CourseMapper;
import com.xmy.study.service.ICourseService;
import com.xmy.study.util.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDate;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * <p>
 * 课程表 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2023-05-24
 */
@RestController
@RequestMapping("/api/admin/eduCourse")
public class CourseController {

    @Autowired
    IdWorker idWorker;

    @Autowired
    ICourseService eduCourseService;

    @Autowired
    CourseMapper courseMapper;

    @Value("${uploadFile.location}")
    private String uploadFileLocation;
    @PostMapping("newEduCourse")
    @ApiOperation("新增课程信息")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "name", value = "名称", required = true, dataType = "String"),
//            @ApiImplicitParam(name = "volume", value = "分册", required = true, dataType = "String"),
//            @ApiImplicitParam(name = "des", value = "描述", required = true, dataType = "String"),
////            @ApiImplicitParam(name = "coverImg", value = "封面图", required = true, dataType = "String"),
////            @ApiImplicitParam(name = "status", value = "状态：1启用,0关闭，", required = false, dataType = "String"),
//            @ApiImplicitParam(name = "sort", value = "排序", required = false, dataType = "String"),
//            @ApiImplicitParam(name = "courseVersionId", value = "版本", required = false, dataType = "String"),
//            @ApiImplicitParam(name = "periodId", value = "学段", required = false, dataType = "String"),
//            @ApiImplicitParam(name = "yearClassId", value = "年级", required = false, dataType = "String"),
//            @ApiImplicitParam(name = "gradeSection", value = "年段：0幼儿园，1小学，2初中，3高中", required = false, dataType = "String"),
//            @ApiImplicitParam(name = "yearPart", value = "年份", required = false, dataType = "String"),
//            @ApiImplicitParam(name = "quarterNum", value = "学期", required = false, dataType = "String"),
//            @ApiImplicitParam(name = "classTypeId", value = "班型", required = false, dataType = "String"),
////            @ApiImplicitParam(name = "createdId", value = "创建人id", required = false, dataType = "String")
//    })
    public Result saveEduCourse(@RequestBody Course eduCourse) {
//        eduCourse.setId(idWorker.nextId());
        eduCourse.setStatus(1);
//        if (file != null) {
//            LocalDate today = LocalDate.now();
//            String audioLink = "/cover_image/" + today;
//            String uploadUrl = uploadFileLocation + audioLink;
//            File fileUp = new File(uploadUrl);
//            // 若不存在则创建该文件夹
//            if (!fileUp.exists()) {
//                fileUp.mkdirs();
//            }
//            String wordStr = UUID.randomUUID().toString().replaceAll("-", "");
//            //获取上传文件的后缀名
//            String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
//            String filename = "";
//            try {
//                filename = wordStr + fileType;
//                file.transferTo(new File(uploadUrl, filename));
//            } catch (Exception e) {
//                e.printStackTrace();
//                System.err.println(e.getMessage());
//                return new Result(Code.ERROR, "", "上传失败");
//            }
//
//            audioLink = audioLink + filename;
//            eduCourse.setCoverImg(audioLink);
//        }
        eduCourseService.save(eduCourse);
        return new Result(Code.OK, null, "课程信息新增成功~");
    }

    @GetMapping("getEduCourse")
    @ApiOperation("查询课程信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名称", required = false, dataType = "String"),
            @ApiImplicitParam(name = "yearPart", value = "年份", required = false, dataType = "String"),
            @ApiImplicitParam(name = "quarterNum", value = "学期", required = false, dataType = "String"),
            @ApiImplicitParam(name = "yearClassId", value = "年级", required = false, dataType = "String"),
            @ApiImplicitParam(name = "classTypeId", value = "班型", required = false, dataType = "String"),
    })
    public Result searchEduCourse(@RequestParam Map reMap) {
        Integer pageNum = StringUtils.isEmpty((String) reMap.get("pageNum")) ? 1 : Integer.valueOf((String) reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String) reMap.get("pageSize")) ? 10 : Integer.valueOf((String) reMap.get("pageSize"));
        Page<Course> iPage = new Page<>(pageNum, pageSize);

        String name = (String) reMap.get("name");
        String yearPart = (String) reMap.get("yearPart");
        String classTypeId = (String) reMap.get("classTypeId");
        String quarterNum = (String) reMap.get("quarterNum");
        String yearClassId = (String) reMap.get("yearClassId");

        QueryWrapper<Course> queryWrapper = new QueryWrapper();

        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
        queryWrapper.eq(StringUtils.isNotBlank(classTypeId), "class_type_id", classTypeId);
        queryWrapper.eq(StringUtils.isNotBlank(yearClassId), "year_class_id", yearClassId);
        queryWrapper.orderByDesc("id");
        eduCourseService.page(iPage, queryWrapper);
        for (Course course : iPage.getRecords()) {
            course.setCourseVersionName(courseMapper.getVersionName(course.getCourseVersionId()));
            course.setClassTypeName(courseMapper.getClassTypeName(course.getClassTypeId()));
            course.setPeriodName(courseMapper.getPeriodName(course.getPeriodId()));
        }
        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()));
    }

    @DeleteMapping("delEduCourse")
    @ApiOperation("删除课程信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "名称", required = true, dataType = "String"),
    })
    public Result removeEduCourse(@RequestParam("id") Long id) {
        Course eduCourse = eduCourseService.getById(id);
        if (Objects.isNull(eduCourse)) {
            return new Result(Code.EXP_ERROR, Code.EXP_MSG, "该课程不存在");
        }
        eduCourseService.removeById(id);
        return new Result(Code.OK, null, "课程信息删除成功~");
    }

    @PostMapping("updateEduCourse")
    @ApiOperation("修改课程信息")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "id", value = "课程id", required = true, dataType = "String"),
//            @ApiImplicitParam(name = "name", value = "名称", required = true, dataType = "String"),
//            @ApiImplicitParam(name = "volume", value = "分册", required = true, dataType = "String"),
//            @ApiImplicitParam(name = "des", value = "描述", required = true, dataType = "String"),
////            @ApiImplicitParam(name = "coverImg", value = "封面图", required = true, dataType = "String"),
////            @ApiImplicitParam(name = "status", value = "状态：1启用,0关闭，", required = false, dataType = "String"),
//            @ApiImplicitParam(name = "sort", value = "排序", required = false, dataType = "String"),
//            @ApiImplicitParam(name = "courseVersionId", value = "版本", required = false, dataType = "String"),
//            @ApiImplicitParam(name = "periodId", value = "学段", required = false, dataType = "String"),
//            @ApiImplicitParam(name = "yearClassId", value = "年级", required = false, dataType = "String"),
//            @ApiImplicitParam(name = "gradeSection", value = "年段：0幼儿园，1小学，2初中，3高中", required = false, dataType = "String"),
//            @ApiImplicitParam(name = "yearPart", value = "年份", required = false, dataType = "String"),
//            @ApiImplicitParam(name = "quarterNum", value = "学期", required = false, dataType = "String"),
//            @ApiImplicitParam(name = "classTypeId", value = "班型", required = false, dataType = "String"),
////            @ApiImplicitParam(name = "createdId", value = "创建人id", required = false, dataType = "String")
//    })
    public Result updateEduCourse(@RequestBody Map reMap) {
        String id = reMap.get("id").toString();
        String name = "";
        if (reMap.get("name") != null) {
            name = reMap.get("name").toString();
        }
        String volume = "";
        if (reMap.get("volume") != null) {
            volume = reMap.get("volume").toString();
        }
        String des = "";
        if (reMap.get("des") != null) {
            des = reMap.get("des").toString();
        }
        String sort = "";
        if (reMap.get("sort") != null) {
            sort = reMap.get("sort").toString();
        }
        String courseVersionId = "";
        if (reMap.get("courseVersionId") != null) {
            courseVersionId = reMap.get("courseVersionId").toString();
        }
        String periodId = "";
        if (reMap.get("periodId") != null) {
            periodId = reMap.get("periodId").toString();
        }
        String yearClassId = "";
        if (reMap.get("yearClassId") != null) {
            yearClassId = reMap.get("yearClassId").toString();
        }
        String gradeSection = "";
        if (reMap.get("gradeSection") != null) {
            gradeSection = reMap.get("gradeSection").toString();
        }
        String yearPart = "";
        if (reMap.get("yearPart") != null) {
            yearPart = reMap.get("yearPart").toString();
        }
        String quarterNum = "";
        if (reMap.get("quarterNum") != null) {
            quarterNum = reMap.get("quarterNum").toString();
        }
        String classTypeId = "";
        if (reMap.get("classTypeId") != null) {
            classTypeId = reMap.get("classTypeId").toString();
        }

        Course eduCourse = eduCourseService.getById(id);

        if (Objects.isNull(eduCourse)) {
            return new Result(Code.EXP_ERROR, Code.EXP_MSG, "该课程不存在");
        }

        if (reMap.get("name") != null) {
            eduCourse.setName(name);
        }
        if (reMap.get("volume") != null) {
            eduCourse.setVolume(volume);
        }
        if (reMap.get("yearPart") != null) {
            eduCourse.setYearPart(Integer.valueOf(yearPart));
        }
        if (reMap.get("quarterNum") != null) {
            eduCourse.setQuarterNum(Integer.valueOf(quarterNum));
        }
        if (reMap.get("yearClassId") != null) {
            eduCourse.setYearClassId(Integer.valueOf(yearClassId));
        }
        if (reMap.get("courseVersionId") != null) {
            eduCourse.setCourseVersionId(Long.valueOf(courseVersionId));
        }
        if (reMap.get("classTypeId") != null) {
            eduCourse.setClassTypeId(Long.valueOf(classTypeId));
        }
        if (reMap.get("periodId") != null) {
            eduCourse.setPeriodId(Long.valueOf(periodId));
        }
        if (reMap.get("des") != null) {
            eduCourse.setDes(des);
        }
        if (reMap.get("gradeSection") != null) {
            eduCourse.setGradeSection(Integer.valueOf(gradeSection));
        }

        if (reMap.get("sort") != null) {
            //判断是否为数字
            Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
            Boolean sortB = pattern.matcher(sort).matches();
            if (!sortB) {
                return new Result(Code.SAVE_ERROR, Code.SAVE_ERROR_MSG, "请正确输入排序号，例如：1");
            }
            eduCourse.setSort(Integer.valueOf(sort));
        }

//        if (file != null) {
//            if (eduCourse.getCoverImg() != null) {
//                ImagesUtil imagesUtil = new ImagesUtil();
//                //        删除原本的图片
//                String imgPath = uploadFileLocation;
//                imagesUtil.pathFile = imgPath;
//                String picOld = eduCourse.getCoverImg();
//                String out = picOld.replace(imgPath, "");
//                imagesUtil.delete(out);
//            }
//            LocalDate today = LocalDate.now();
//            String audioLink = "/cover_image/" + today;
//            String uploadUrl = uploadFileLocation + audioLink;
//            File fileUp = new File(uploadUrl);
//            // 若不存在则创建该文件夹
//            if (!fileUp.exists()) {
//                fileUp.mkdirs();
//            }
//            String wordStr = UUID.randomUUID().toString().replaceAll("-", "");
//            //获取上传文件的后缀名
//            String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
//            String filename = "";
//            try {
//                filename = wordStr + fileType;
//                file.transferTo(new File(uploadUrl, filename));
//            } catch (Exception e) {
//                e.printStackTrace();
//                System.err.println(e.getMessage());
//                return new Result(Code.ERROR, "", "上传失败");
//            }
//
//            audioLink = audioLink + filename;
//            eduCourse.setCoverImg(audioLink);
//        }

        eduCourseService.updateById(eduCourse);
        return new Result(Code.OK, null, "课程信息修改成功~");
    }

    @GetMapping("infoCourse")
    @ApiOperation("课程信息")
    public Result getInfo(@RequestBody Map reMap) {
        try {
            String id = reMap.get("id").toString();
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("id", id);
            Course one = eduCourseService.getOne(queryWrapper);
            return new Result(Code.OK, one, "课程信息~");
        } catch (Exception e) {
//            throw new RuntimeException(e);
            return new Result(Code.ERROR, null, "暂时没有课程信息哦！~");
        }

    }
}
